package com.example.util;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import javax.script.ScriptException;
import java.io.IOException;
import java.util.Date;

public class LoginUtil {

    public static void main(String[] args) {
        HttpClient httpClient = new HttpClient();
        httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        httpClient.getParams().setParameter(HttpMethodParams.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0");

        String url = "https://passport.baidu.com/v2/?login";
        HttpMethod getMethod = new GetMethod(url);
        try {
            httpClient.executeMethod(getMethod);
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            getMethod.releaseConnection();
        }

        try {
            String gid = ScriptEngineUtil.guidRandom();
            String token = getToken(httpClient, gid);
            String[] keyArr = getRSAKeyAndPubKey(httpClient, gid, token);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ScriptException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

    }

    /**
     * 百度登录先获得Token
     *
     * @param gid 随机ID
     * @return
     */
    public static String getToken(HttpClient client, String gid) {
        String tt = "" + (new Date()).getTime();
        String baseUrl = "https://passport.baidu.com/v2/api/?getapi&tpl=pp&apiver=v3&tt=%s&class=login&gid=%s&loginversion=v4&logintype=basicLogin&traceid=&callback=bd__cbs__bsbrf9";
        String requestUrl = String.format(baseUrl, tt, gid);
        HttpMethod getMethod = new GetMethod(requestUrl);
        try {
            client.executeMethod(getMethod);
            if (!(getMethod.getStatusCode() == HttpStatus.SC_OK)) return "";
            String jsonStr = getMethod.getResponseBodyAsString();
            jsonStr = jsonStr.substring(jsonStr.indexOf('(') + 1, jsonStr.lastIndexOf(')'));

            JSONObject jsonObj = JSONObject.parseObject(jsonStr);
            String token = JSONObject.parseObject(jsonObj.getString("data")).getString("token").toString();
            return token;
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            getMethod.releaseConnection();
        }
        return "";
    }

    /**
     * 百度登录获得RSA加密公钥和Pubkey
     * @param client
     * @param gid
     * @param token
     * @return
     */
    public static String[] getRSAKeyAndPubKey(HttpClient client, String gid, String token)
    {
        String tt = "" + (new Date()).getTime();
        String baseUrl = "https://passport.baidu.com/v2/getpublickey?token=%s&tpl=dev&apiver=v3&tt=%s&gid=%s&loginversion=v4&traceid=&callback=bd__cbs__fbzosu";
        String requestUrl = String.format(baseUrl, token, tt, gid);
        HttpMethod getMethod = new GetMethod(requestUrl);
        try
        {
            client.executeMethod(getMethod);
            if(!(getMethod.getStatusCode() == HttpStatus.SC_OK)) return null;
            String jsonStr = getMethod.getResponseBodyAsString();
            jsonStr = jsonStr.substring(jsonStr.indexOf('(') + 1, jsonStr.lastIndexOf(')'));

            JSONObject jsonObj = JSONObject.parseObject(jsonStr);
            String rsaKey = jsonObj.getString("key");
            String pubKey = jsonObj.getString("pubkey");

            return new String[]{rsaKey, pubKey};
        } catch (HttpException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally
        {
            getMethod.releaseConnection();
        }
        return null;
    }


}
